package com.seraph.td.socket;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServiceSocketTools {
	public static void main(String[] args){
		System.out.println("BEGIN -----------------ACCPET");
		
		ServerSocket socket = null;
		String fileName = "default.png";
		FileOutputStream out = null;
		byte[] buffer = new byte[1024];
		InputStream in;
		int len;
		try {
			socket = new ServerSocket(8199);
			int count =0;
			System.out.println("BEGIN");
			while(true){
				Socket s = socket.accept();
				count++;
				in = s.getInputStream();
				//获取文件名
				
				len = in.read(buffer);
				String str = new String(buffer,0,len);
				int index = str.indexOf("data begin :\n");
				String data = str.substring(index+"data begin :\n".length());
				fileName = str.substring(0, index);
				System.out.println("filename="+fileName+"\t----count="+count);
				out = new FileOutputStream(fileName);
				out.write(data.getBytes());
				
				//
				//temp
				
				File file = new File(fileName);
				if(file.exists())
					file.delete();
				file.createNewFile();
				out = new FileOutputStream(fileName);
				while((len = in.read(buffer)) != -1) {
					out.write(buffer, 0, len);
				}
				out.flush();
				out.close();
				s.close();
			}
			
	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("ERROR");
		}
		
//		socket.
	}
}
